package com.server.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
@Component
public class FFmpegVideoUtil {
    private static String pixel;

    private  static String kb;

    private  static String frameNumber;

    @Value("${ffmpeg.pixel}")
    public void setPixel(String value){
        pixel = value;
    }

    @Value("${ffmpeg.kb}")
    public void setKb(String value){
        kb = value;
    }
    @Value("${ffmpeg.frameNumber}")
    public void setFrameNumber(String value){
        frameNumber =value;
    }

    public static  void toCompressFile(String convertFile,String targetFile){
        try{
            Runtime runtime = Runtime.getRuntime();
            /**将视频压缩为 每秒15帧 平均码率600k 画面的宽与高 为1280*720*/
//            String cutCmd="ffmpeg -i " + convertFile + " -r "+pixel+" -b:v "+kb+"  -s "+frameNumber+" "+ targetFile;
            String cutCmd="ffmpeg -i " + convertFile + " -vcodec h264 -r "+pixel+" -b:v "+kb+" "+ targetFile;
            log.info("cutCmd:"+cutCmd);
            runCmd(cutCmd);
            log.info("文件："+convertFile+" 视屏压缩完成");
        }catch(Exception e){
            e.printStackTrace();
            log.info("压缩文件出现异常："+e.getMessage());
        }
    }

    /**
     * linux下 ffmpeg命令的执行方法
     *
     * @param command 执行的命令字符串
     */
    public static void runCmd(String command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line;
            log.info("开始执行");
            while ((line = br.readLine()) != null){
                log.info(line);
            }
            log.info("执行结束");
            int exitVal = proc.waitFor();
            log.info("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            System.out.println(t);
            t.printStackTrace();
        }

    }

}
